package com.site.util;

import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaochi
 * @date 2022/4/10 13:39
 * @desc CopyUtil（属性复制）
 */
public class CopyUtil {

    /**
     * 单个复制
     * @param source
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T>T copy(Object source,Class<T> clazz){
        if (source == null){
            return null;
        }
        T dest = null;
        try {
            dest = clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        BeanUtils.copyProperties(source,dest);
        return dest;
    }

    /**
     * 集合复制
     * @param source
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T>List<T> copy(List<?> source,Class<T> clazz){
        List<T> target = new ArrayList<>();
        if (!CollectionUtils.isEmpty(source)){
            for (Object c : source){
                target.add(copy(c,clazz));
            }
        }
        return target;
    }
}
